package com.example.myapplication.storage;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.myapplication.R;
import com.example.myapplication.storage.database.UserDBHelper;
import com.example.myapplication.storage.entity.User;
import com.example.myapplication.utils.ToastUtils;

import java.util.List;

public class SQLiteDatabaseUsageActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView tvMessage;

    private SQLiteDatabase database;

    private String databaseFilePath;

    private UserDBHelper dbHelper;

    private EditText etName;
    private EditText etAge;
    private EditText etHeight;
    private EditText etWeight;
    private CheckBox cbMarried;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_sqlite_database_usage);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        findViewById(R.id.btn_create_database).setOnClickListener(this);
        findViewById(R.id.btn_delete_database).setOnClickListener(this);
        findViewById(R.id.btn_create_table).setOnClickListener(this);
        findViewById(R.id.btn_delete_table).setOnClickListener(this);

        tvMessage = findViewById(R.id.tv_message);

        // 生成一个测试数据库的保存路径
        databaseFilePath = getFilesDir() + "/test.db";

        etName = findViewById(R.id.et_name);
        etAge = findViewById(R.id.et_age);
        etHeight = findViewById(R.id.et_height);
        etWeight = findViewById(R.id.et_weight);
        cbMarried = findViewById(R.id.cb_married);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);
        findViewById(R.id.btn_load).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_create_database) {
            // 创建或打开数据库，如果数据库存在就打开，否则，创建数据库
            database = openOrCreateDatabase(databaseFilePath, Context.MODE_PRIVATE, null);
            String desc = null;
            if (database == null) {
                desc = String.format("数据库%s创建失败！", databaseFilePath);
            } else {
                desc = String.format("数据库%s创建成功！", database.getPath());
            }
            tvMessage.setText(desc);
        } else if (v.getId() == R.id.btn_delete_database) {
            // 删除数据库
            boolean succeed = deleteDatabase(databaseFilePath);
            String desc = String.format("删除数据库%s失败！", databaseFilePath);
            if (succeed) {
                desc = String.format("删除数据库%s成功！", databaseFilePath);
            }
            tvMessage.setText(desc);
        } else if (v.getId() == R.id.btn_save) {
            User user = composeUser();
            long insertedRows = dbHelper.insert(user);
            if (insertedRows == -1) {
                ToastUtils.show(this,  "添加用户失败！");
            } else {
                ToastUtils.show(this,  "添加用户成功！");
            }
        } else if (v.getId() == R.id.btn_delete) {
            String name = etName.getText().toString();
            long deletedRows = dbHelper.deleteByName(name);
            if (deletedRows == 0) {
                ToastUtils.show(this, "没有删除到符合条件的记录！");
            } else if (deletedRows > 0) {
                ToastUtils.show(this, String.format("删除成功！共删除%d条记录。", deletedRows));
            } else {
                ToastUtils.show(this, "删除记录失败！");
            }
        } else if (v.getId() == R.id.btn_update) {
            User user = composeUser();
            long affectedRows = dbHelper.updateByName(user);
            if (affectedRows == 0) {
                ToastUtils.show(this, "没有更新到符合条件的记录！");
            } else if (affectedRows > 0) {
                ToastUtils.show(this, String.format("更新成功！共更新%d条记录。", affectedRows));
            } else {
                ToastUtils.show(this, "更新记录失败！");
            }
        } else if (v.getId() == R.id.btn_query) {
            List<User> userList = dbHelper.queryAll();
            for (User user : userList) {
                Log.d("SQLiteDatabaseUsage", user.toString());
            }
        } else if (v.getId() == R.id.btn_load) {
            String name = etName.getText().toString();
            List<User> userList = dbHelper.queryByName(name);
            if (userList.isEmpty()) {
                ToastUtils.show(this, "没有查询到相同名称的记录！");
                return;
            } else {
                ToastUtils.show(this, String.format("查询用户信息成功！共查询到%d个用户。", userList.size()));
            }
            User user = userList.get(0);
            etAge.setText(String.valueOf(user.getAge()));
            etHeight.setText(String.valueOf(user.getHeight()));
            etWeight.setText(String.valueOf(user.getWeight()));
            cbMarried.setChecked(user.getMarried());
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        dbHelper = UserDBHelper.getInstance(this);
        dbHelper.openWritableConnection();
        dbHelper.openReadableConnection();
    }

    @Override
    protected void onStop() {
        super.onStop();
        dbHelper.closeConnection();
    }

    private User composeUser() {
        User user = new User();
        user.setName(etName.getText().toString());
        try {
            String age = etAge.getText().toString();
            if (!age.isEmpty()) {
                user.setAge(Integer.parseInt(age));
            }
        } catch (NumberFormatException e) {
            ToastUtils.show(this, "年龄只能为整数！");
            throw e;
        }
        try {
            String height = etHeight.getText().toString();
            if (!height.isEmpty()) {
                user.setHeight(Integer.parseInt(height));
            }
        } catch (NumberFormatException e) {
            ToastUtils.show(this, "身高只能为整数！");
            throw e;
        }
        try {
            String weight = etWeight.getText().toString();
            if (!weight.isEmpty()) {
                user.setWeight(Float.parseFloat(weight));
            }
        } catch (NumberFormatException e) {
            ToastUtils.show(this, "体重只能为浮点数！");
            throw e;
        }
        user.setMarried(cbMarried.isChecked());
        return user;
    }
}